import XEUtils from 'xe-utils'
import { deepClone } from '@/utils/util'
import { containers } from './container-widgets'
import { basicFields } from './basic-fields'
import { advancedFields } from './advanced-fields'

export * from './container-widgets'
export * from './basic-fields'
export * from './advanced-fields'

export const customFields = []

export const chartContainers = []

export const chartWidgets = []


export function addContainerWidgetSchema(containerSchema) {
  containers.push(containerSchema)
}

export function addBasicFieldSchema(fieldSchema) {
  basicFields.push(fieldSchema)
}

export function addAdvancedFieldSchema(fieldSchema) {
  advancedFields.push(fieldSchema)
}

export function addCustomWidgetSchema(widgetSchema) {
  customFields.push(widgetSchema)
}

export function addChartContainerSchema(chartContainerSchema) {
  chartContainers.push(chartContainerSchema)
}

export function addChartSchema(chartSchema) {
  chartWidgets.push(chartSchema)
}

const defaultDynamicOptions = {
  spaceStyle: {
    margin: '0 0 0 0',
    padding: '0 0 0 0',
  },
  sizeStyle: {
    width: '100%',
    height: '100%',
    minWidth: 'auto',
    minHeight: 'auto',
    maxWidth: 'auto',
    maxHeight: 'auto',
    overflow: 'visible',
  },
  svvo: {
    id: '',
    enabled: true,
  },
}

export const schemaType = {
  containers,
  basicFields,
  advancedFields,
}

// 定义 SchemaConfig 接口
interface SchemaConfig {
  schemaType: any;  // 指定适当的类型
  fieldPath: string;
  value: any;       // 指定适当的类型
  filter?: (item: any) => boolean;  // 可选的过滤函数
}

/**
 * 根据提供的配置向schema添加属性。
 * 此函数允许动态地向schema项添加样式或其他属性。
 *
 * @param {SchemaConfig} config - 包含schema类型、字段路径、要设置的值以及可选的过滤函数的配置对象。
 */
export function addAttrToSchemaWithType(config: SchemaConfig) {
  // 检查是否提供了过滤函数，并应用它来过滤schema项
  config.filter
    ? config.schemaType.filter(config.filter).forEach((item) => {
      // 使用深克隆在指定的字段路径上设置值，以避免直接引用问题
      XEUtils.set(item, config.fieldPath, deepClone(config.value))
    })
    : // 如果没有提供过滤器，将值应用于schema类型的所有项
    config.schemaType.forEach((item) => {
      // 直接在指定的字段路径上设置值，无需过滤
      XEUtils.set(item, config.fieldPath, deepClone(config.value))
    })
}

//给组件动态添加属性
;(function initSchema() {
  // console.log('initSchema');
  addAttrToSchemaWithType({
    schemaType: schemaType.containers,
    fieldPath: 'options.spaceStyle',
    value: defaultDynamicOptions.spaceStyle,
  })
  addAttrToSchemaWithType({
    schemaType: schemaType.containers,
    fieldPath: 'options.sizeStyle',
    value: defaultDynamicOptions.sizeStyle,
  })
  /*addAttrToSchemaWithType({
    schemaType: schemaType.basicFields,
    fieldPath: 'options.svvo',
    value: defaultDynamicOptions.svvo,
    filter: (item) => {
      const types = ['select', 'radio', 'check-box']
      return types.includes(item.type)
    },
  })*/
})()
